package com.sskj.gocoin.v.fragment;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.Guideline;
import android.support.design.widget.TabLayout;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.ClassicsHeader;
import com.sskj.gocoin.common.MoneyValueFilter;
import com.sskj.gocoin.common.TabItem;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.common.rxbus2.NetSubScriber;
import com.sskj.gocoin.common.widget.ToolBarLayout;
import com.sskj.gocoin.m.bean.Currency;
import com.sskj.gocoin.m.bean.LevelBean;
import com.sskj.gocoin.m.bean.StockBean;
import com.sskj.gocoin.m.bean.bean.LevelTransactionCodePk;
import com.sskj.gocoin.m.bean.bean.NewStock;
import com.sskj.gocoin.p.fragment.LevelTransactionFragmentPst;
import com.sskj.gocoin.utils.CheckUtil;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.EditChangeUtil;
import com.sskj.gocoin.utils.GsonUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.RxSchedulersHelper;
import com.sskj.gocoin.utils.TipUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.LoginActivity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.MarketDetailActivity;
import com.sskj.gocoin.v.activity.TradeActivity;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.gocoin.v.base.BaseViewPagerFragment;
import com.sskj.gocoin.v.widget.mychart.AutoSizeTextView;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

/**
 * ProjectName：ioaex
 * DESC: (类描述)  合约交易
 * Created by 李岩 on 2018/8/31 0031
 * updateName:(修改人名称)
 * updateTime:(修改时间)
 * updateDesc:(修改内容)
 */
public class LevelTransactionFragmentX extends BaseFragment<MainActivity, LevelTransactionFragmentPst> implements OnRefreshListener {

    @BindView(R.id.toolBar)
    ToolBarLayout mToolBar;
    @BindView(R.id.top_stock_price)
    TextView mTopStockPrice;  // 当前币价钱
    @BindView(R.id.top_stock_change_value)
    TextView mTopStockChangeValue;  // 头部变化百分比
    @BindView(R.id.top_stock_hight_price)
    TextView mTopStockHightPrice;  // 头部  高
    @BindView(R.id.top_stock_low_price)
    TextView mTopStockLowPrice;  // 头部 低
    @BindView(R.id.transaction_approximate_top)
    TextView mTransactionApproximateTop;  // 约等于人民币
    @BindView(R.id.risk_ratio)
    TextView mRiskRatio;
    @BindView(R.id.spinner_left)
    Spinner mSpinnerLeft;
    @BindView(R.id.transaction_left_type)
    TextView mTransactionLeftType;
    @BindView(R.id.linearlayout_left)
    LinearLayout mLinearlayoutLeft;
    @BindView(R.id.spinner_right)
    Spinner mSpinnerRight;
    @BindView(R.id.rlRightEditPrice)
    RelativeLayout mRlRightEditPrice;
    @BindView(R.id.transaction_right_type)
    TextView mTransactionRightType;
    @BindView(R.id.linearlayout_right)
    LinearLayout mLinearlayoutRight;
    @BindView(R.id.transaction_record_all)
    TextView mTransactionRecordAll;  // 全部
    @BindView(R.id.slidingTabLayout)
    CommonTabLayout mSlidingTabLayout;
    @BindView(R.id.trade_content)
    FrameLayout mTradeContent;
    @BindView(R.id.smartrefresh)
    SmartRefreshLayout mSmartrefresh;
    @BindView(R.id.price_type_a)
    RadioButton priceTypeA;  // 做多--现在
    @BindView(R.id.price_type_b)
    RadioButton priceTypeB;  // 做空--现在
    @BindView(R.id.radioGroup)
    RadioGroup mRadioGroup;
    @BindView(R.id.transaxtion_sj)
    RadioButton transaxtionSj;  // 市价--现在
    @BindView(R.id.transaxtion_xj)
    RadioButton transaxtionXj;  // 限价--现在
    @BindView(R.id.radioGroup2)
    RadioGroup mRadioGroup2;
    @BindView(R.id.transction_price_editText)
    EditText transctionPriceEditText;  // 限价输入框情况--现在
    @BindView(R.id.transction_increase_price)
    TextView transctionIncreasePrice;  // -  减号
    @BindView(R.id.cutting_line)
    TextView cuttingLine;
    @BindView(R.id.transction_decrease_price)
    TextView transctionDecreasePrice;  // +  加号
    @BindView(R.id.rlEditPrice)
    RelativeLayout rlEditPrice;
    @BindView(R.id.transction_price_textView)
    TextView transctionPriceTextView;  // 市价  输入框情况--现在
    @BindView(R.id.transaction_approximate)
    TextView transactionApproximate;
    @BindView(R.id.transction_sum_editText)
    EditText transctionSumEditText;  // 输入框数量--现在
    @BindView(R.id.transaction_type)
    TextView transactionType;// 当前币名字--现在
    @BindView(R.id.transaction_item_balance)
    TextView transactionItemBalance;  // 可用--现在
    @BindView(R.id.transaction_count)
    AutoSizeTextView transactionCount;  // 交易额
    @BindView(R.id.transaction_sell_list)
    RecyclerView transactionSellList;  // 盘口第一个RecyclerView
    @BindView(R.id.transaction_now_price)
    TextView transactionNowPrice;  // 盘口最新价
    @BindView(R.id.transaction_rmb)
    TextView transactionRmb;  // 盘口约等于人民币
    @BindView(R.id.transaction_buy_list)
    RecyclerView transactionBuyList;  // 盘口第二个RecyclerView
    @BindView(R.id.loading_layout)
    FrameLayout loadingLayout;
    @BindView(R.id.guideline)
    Guideline guideline;
    @BindView(R.id.address_list_content_delete)
    TextView addressListContentDelete;
    @BindView(R.id.target_profit_value)
    TextView targetProfitValue;  // 止盈点位--现在
    @BindView(R.id.textView29)
    TextView textView29;
    @BindView(R.id.stop_loss_value)
    TextView stopLossValue;  // 止损点位--现在
    @BindView(R.id.etStopWin)
    TextInputEditText etStopWin;  // 止盈点位--现在
    @BindView(R.id.inputLayoutWin)
    TextInputLayout inputLayoutWin;
    @BindView(R.id.etStopLoss)
    TextInputEditText etStopLoss;  // 止损点位--现在
    @BindView(R.id.inputLayoutLoss)
    TextInputLayout inputLayoutLoss;
    @BindView(R.id.transaction_input2)
    Button transactionInput2;  // 做多按钮--现在
    @BindView(R.id.transaction_output2)
    Button transactionOutput2;  // 做空--现在

    @BindView(R.id.multipleTabLayout)
    TabLayout multipleTabLayout;

    public boolean flag = true;  // 用于判断websocket是否关闭，默认开启

    //    public boolean isLimitPrice = true; //是否市价 默认非市价
    private String wallet = "0.00";
    /**
     * 做多价格类型 ： 1: 市价   ；   2 ： 限价
     * 默认 限价
     */
    private int mLeftType = 1;
    /**
     * 做空价格类型 ： 1: 市价   ；   2 ： 限价
     * 默认 限价
     */
    private int mRightType = 1;
    /**
     * 下单需要的数据
     */
    private StockBean mStockBean;
    /**
     * 当前股票的当前做多价格
     */
    private double mCurrentPriceLeftD;
    /**
     * 当前股票的当前做空价格
     */
    private double mCurrentPriceRightD;
    DecimalFormat mFormat = new DecimalFormat("0.0000");
    DateFormat dateFormat = new SimpleDateFormat("HH:mm MM/dd");
    /**
     * 计算的交易额
     */
    private double mSumPrice;
    private String name = "";
    private String mark = "";


    private double price;
    private double priceAddOrIncre;  // 记录用户加减价格
    private String code = "";
    private double leftMaxNum; //做多可输入的最大数量
    private double rightMaxNum; //做空可输入的最大数量
    private double minNum; //可输入的最小数量
    private int minDealNum; //可交易的最小数量
    private MaterialDialog customTip;
    private String unit = "USDT";
    private double leverage = 1; //杠杆
    private double shouPer; //手续费
    private String baoPer = "100%";
    /**
     * 当前币种的浮动点差价格
     */
    private double mSpreadPrice;
    private double unitPrice;
    private int mStoplossMax;
    private int mStopwinMax;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private BaseAdapter<LevelTransactionCodePk.PkCode> sellAdapter;// 盘口第一个RecyclerView
    private BaseAdapter<LevelTransactionCodePk.PkCode> buyAdapter;
    public List<LevelTransactionCodePk.PkCode> sellList = new ArrayList<>();
    public List<LevelTransactionCodePk.PkCode> buyList = new ArrayList<>();

    private boolean isHideChange;

    private boolean isResume;

    public static LevelTransactionFragmentX newInstance() {
        LevelTransactionFragmentX fragment = new LevelTransactionFragmentX();
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_level_transaction_x;
    }

    @Override
    public LevelTransactionFragmentPst getPresenter() {
        return new LevelTransactionFragmentPst();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isHideChange = true;
            onLoad();
        } else {
            loadingLayout.setVisibility(View.VISIBLE);
            mPresenter.closeWebSocket();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        onLoad();
        isResume = true;
    }

    public void onLoad() {
        if (isHideChange && isResume) {
            return;
        } else {
            mPresenter.initWebSocket(code);
            if (!TextUtils.isEmpty(MyAppLication.getMobile()) && MyAppLication.isLogin()) {
                mPresenter.getUserInfo();
                if (!TextUtils.isEmpty(code)) {
                    mPresenter.getLeveRange(code);
                }
                updateFragment();
            }
        }
    }


    @Override
    public void initView() {
//        code = mActivity.mCurrentStockName;
//        if (!TextUtils.isEmpty(code)) {
//            code = code + "_usdt";
//        }

        ClassicsHeader classicsHeader = new ClassicsHeader(getActivity());
        classicsHeader.setBackgroundColor(getResources().getColor(R.color.background));
        mSmartrefresh.setRefreshHeader(classicsHeader);
        mSmartrefresh.setEnableLoadMore(false);
        mSmartrefresh.setOnRefreshListener(this);

        mToolBar.setRightButtonOnClickLinster(view12 -> { //跳转股票详情
            if (mActivity.mCurrentStock != null) {
                MarketDetailActivity.start(getActivity(), (NewStock) mActivity.mCurrentStock, 1);
            }
        });

        mToolBar.setLeftButtonOnClickLinster(view1 -> {
            mActivity.openDrawerLayout();
            mPresenter.closeWebSocket();
            loadingLayout.setVisibility(View.VISIBLE);
        });
        mStockBean = new StockBean();
        upDate();

        Bundle args = new Bundle();
        NewTradePositionFragment newTradePositionFragment = new NewTradePositionFragment();
        args.putString("code", mark);
        newTradePositionFragment.setArguments(args);
        mFragments.add(newTradePositionFragment);  // 持仓

//        FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
//        FragmentTransaction beginTransaction =   fragmentManager.beginTransaction();
//        beginTransaction.add(R.id.trade_content, newTradePositionFragment);
//        beginTransaction.addToBackStack(null);
//        beginTransaction.commit();

        Bundle argTrade = new Bundle();
        TradeDeputeFragment tradeDeputeFragment = new TradeDeputeFragment();
        argTrade.putString("code", mark);
        tradeDeputeFragment.setArguments(argTrade);
        mFragments.add(tradeDeputeFragment); // 委托
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX210), 0, 0));
//        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX211), 0, 0));
        mSlidingTabLayout.setTabData(tabItems, mActivity, R.id.trade_content, mFragments);
//        slidingTabLayout.setCurrentTab(1);
        transctionPriceEditText.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});
//        mTransctionRightPriceEditText.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});
        transactionSellList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, true));
        transactionBuyList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));


        buyAdapter = new BaseAdapter<LevelTransactionCodePk.PkCode>(R.layout.item_recycler_transaction_sell, new ArrayList<>(), transactionBuyList) {
            @Override
            public void bind(ViewHolder holder, LevelTransactionCodePk.PkCode item) {
                holder.setText(R.id.transaction_sell_id, holder.getLayoutPosition() + 1 + "");
                holder.setText(R.id.transaction_sell_price, NumberUtil.keep4(item.getPrice()));
                holder.setText(R.id.transaction_sell_num, NumberUtil.keep4(item.getTotalSize()));
                holder.setTextColor(R.id.transaction_sell_price, ContextCompat.getColor(getActivity(), R.color.market_up));
                if (item.isShow()) {
                    colorAnimGreen(holder.getView(R.id.transaction_sell_price), true);
                    colorAnimGreen(holder.getView(R.id.transaction_sell_num), false);
                }
            }
        };

        sellAdapter = new BaseAdapter<LevelTransactionCodePk.PkCode>(R.layout.item_recycler_transaction_sell, new ArrayList<>(), transactionSellList) {
            @Override
            public void bind(ViewHolder holder, LevelTransactionCodePk.PkCode item) {
                holder.setText(R.id.transaction_sell_id, holder.getLayoutPosition() + 1 + "");
                holder.setText(R.id.transaction_sell_price, NumberUtil.keep4(item.getPrice()));
                holder.setText(R.id.transaction_sell_num, NumberUtil.keep4(item.getTotalSize()));
                holder.setTextColor(R.id.transaction_sell_price, ContextCompat.getColor(getActivity(), R.color.market_down));
                if (item.isShow()) {
                    colorAnim(holder.getView(R.id.transaction_sell_price), true);
                    colorAnim(holder.getView(R.id.transaction_sell_num), false);
                }
            }
        };


    }

    @Override
    public void initData() {
        super.initData();
        mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.price_type_a://做多
                    if (mActivity.status != 0) {
                        mActivity.status = 0;
                        etStopWin.setText("");
                        etStopLoss.setText("");
                        transactionInput2.setVisibility(View.VISIBLE);
                        transactionOutput2.setVisibility(View.GONE);
                    }
                    break;
                case R.id.price_type_b://做空
                    if (mActivity.status != 1) {
                        mActivity.status = 1;
                        etStopWin.setText("");
                        etStopLoss.setText("");
                        transactionInput2.setVisibility(View.GONE);
                        transactionOutput2.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        });
        mRadioGroup2.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.transaxtion_sj: // 市价
                    transaxtionSj.setTextColor(ContextCompat.getColor(getContext(), R.color.tip));
                    transaxtionXj.setTextColor(ContextCompat.getColor(getContext(), R.color.text_color));
                    mLeftType = 1;
                    mCurrentPriceLeftD = TextUtils.isEmpty(transctionPriceEditText.getText().toString().trim()) ? 0 : Double.parseDouble(transctionPriceEditText.getText().toString().trim());
                    Log.i("InfoMessage", mCurrentPriceLeftD + App.INSTANCE.getString(R.string.strLevelTransactionFragmentX219));
                    upDate();
                    break;
                case R.id.transaxtion_xj://限价
                    transaxtionSj.setTextColor(ContextCompat.getColor(getContext(), R.color.text_color));
                    transaxtionXj.setTextColor(ContextCompat.getColor(getContext(), R.color.tip));
                    mCurrentPriceLeftD = price;
                    mLeftType = 2;
                    upDate();
                    break;
            }
        });

        //做多按钮
        ClickUtil.click(transactionInput2, () -> { //做多
            mStockBean.otype = 1; //设置做多
            String num = transctionSumEditText.getText().toString().trim();
            if (TextUtils.isEmpty(num)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX220));
                return;
            }
            mStockBean.buynum = Integer.valueOf(num);
            //设置价格
            if (mLeftType == 2) { //限价，选择用户输入的价格
                String newprice = transctionPriceEditText.getText().toString().trim();
                if (TextUtils.isEmpty(newprice)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX221));
                    return;
                } else if (Double.valueOf(newprice) <= 0) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX222));
                    return;
                }
                mStockBean.newprice = newprice;
            } else { //市价，选择股票最新的价格
                mStockBean.newprice = mTopStockPrice.getText().toString().trim();
            }
            //设置做多 价格类型
            mStockBean.type = mLeftType;
            //设置 做多止盈止损
            String stoploss = etStopLoss.getText().toString().trim();
            String stopwin = etStopWin.getText().toString().trim();
            mStockBean.stoploss = TextUtils.isEmpty(stoploss) ? 0 : Double.valueOf(stoploss);
            mStockBean.stopwin = TextUtils.isEmpty(stopwin) ? 0 : Double.valueOf(stopwin);
            placeOrder(mLeftType);
        });
        // 做空按钮
        ClickUtil.click(transactionOutput2, () -> { //做空
            mStockBean.otype = 2;//设置做空
            String num = transctionSumEditText.getText().toString().trim();
            if (TextUtils.isEmpty(num)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX220));
                return;
            }
            mStockBean.buynum = Integer.valueOf(num);
            //设置价格
            if (mLeftType == 2) { //限价，选择用户输入的价格
                String newprice = transctionPriceEditText.getText().toString().trim();
                if (TextUtils.isEmpty(newprice)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX221));
                    return;
                } else if (Double.valueOf(newprice) <= 0) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX222));
                    return;
                }
                mStockBean.newprice = newprice;
            } else { //市价，选择股票最新的价格
                mStockBean.newprice = mTopStockPrice.getText().toString().trim();
            }
            //设置做空 价格类型
            mStockBean.type = mLeftType;
            //设置 做空止盈止损
            String stoploss = etStopLoss.getText().toString().trim();
            String stopwin = etStopWin.getText().toString().trim();
            mStockBean.stoploss = TextUtils.isEmpty(stoploss) ? 0 : Double.valueOf(stoploss);
            mStockBean.stopwin = TextUtils.isEmpty(stopwin) ? 0 : Double.valueOf(stopwin);
            placeOrder(mLeftType);
        });
        // 爆仓说明
        ClickUtil.click(mRiskRatio, () -> {
            customTip = TipUtil.customTip(getActivity(), App.INSTANCE.getString(R.string.strLevelTransactionFragmentX226), App.INSTANCE.getString(R.string.strLevelTransactionFragmentX227) + baoPer + App.INSTANCE.getString(R.string.strLevelTransactionFragmentX228), App.INSTANCE.getString(R.string.strLevelTransactionFragmentX229));
        });
        // 限价输入框
        EditChangeUtil.onChange(transctionPriceEditText, s -> {
            Log.i("InfoMessage", "change:::::");
            mCurrentPriceLeftD = Double.parseDouble(TextUtils.isEmpty(s.toString()) ? "0" : s.toString()) + mSpreadPrice;
            if (mCurrentPriceLeftD <= 0) {
                mCurrentPriceLeftD = mSpreadPrice;
            }
            if (TextUtils.isEmpty(s.toString()) || Double.isInfinite(leftMaxNum) || Double.isNaN(leftMaxNum)) {
                leftMaxNum = 0;
            } else {
                calcuLeftMostNum();
            }
            if (!TextUtils.isEmpty(transctionPriceEditText.getText().toString().trim())) {
                //交易额 计算公式 : 最新价*购买数量/20
                double valueD = Double.valueOf(TextUtils.isEmpty(transctionSumEditText.getText().toString().trim()) ? "0.0" : transctionSumEditText.getText().toString().trim());
                mSumPrice = calcuAllPrice(mCurrentPriceLeftD, valueD);
                transactionCount.setText(getString(R.string.bz_count) + " " + mFormat.format(mSumPrice) + " " + unit);

            }
        });
        // 输入数量输入框
        EditChangeUtil.onChange(transctionSumEditText, editable -> {
            if (!TextUtils.isEmpty(editable.toString())) {
                double valueD = formatDouble(editable);
                if (valueD > leftMaxNum) {
                    String maxNum = String.valueOf((int) leftMaxNum);
                    transctionSumEditText.setText(maxNum);
                    transctionSumEditText.setSelection(maxNum.length());
                } else {
                    //交易额 计算公式 : 最新价*购买数量/20
                    mSumPrice = calcuAllPrice(mCurrentPriceLeftD, valueD);
                    transactionCount.setText(getString(R.string.bz_count) + " " + mFormat.format(mSumPrice) + " " + unit);
                    Log.i("InfoMessage", mCurrentPriceLeftD + "<<<<<<");
                }
            } else { //数量为空，使用最小数量
                mSumPrice = calcuAllPrice(mCurrentPriceLeftD, minNum);
                transactionCount.setText(getString(R.string.bz_count) + mFormat.format(mSumPrice) + unit);
            }
        });
        //做多止盈
        EditChangeUtil.onChange(etStopWin, s -> {
            if (!TextUtils.isEmpty(s.toString())) {
                Double aDouble = Double.valueOf(s.toString());
                if (aDouble < 0) {
                    etStopWin.setText("0");
                }
                if (s.toString().contains(".")) {
                    int pointLength = s.toString().length() - (s.toString().indexOf(".")) - 1;  //获取小数点有几位数字
                    if (pointLength > 4) {
                        etStopWin.setText(NumberUtil.keep4(s.toString()));
                        etStopWin.setSelection(etStopWin.getText().toString().trim().length());
                    }
                }

//                if (aDouble > mStopwinMax) {
//                    String max = String.valueOf(mStopwinMax);
//                    etStopWin.setText(String.valueOf(mStopwinMax));
//                    etStopWin.setSelection(max.length());
//                }
            }
        });
        //做多止损
        EditChangeUtil.onChange(etStopLoss, s -> {
            if (!TextUtils.isEmpty(s.toString())) {
                Double aDouble = Double.valueOf(s.toString());
                if (s.toString().contains(".")) {
                    int pointLength = s.toString().length() - (s.toString().indexOf(".")) - 1;  //获取小数点有几位数字
                    if (pointLength > 4) {
                        etStopLoss.setText(NumberUtil.keep4(s.toString()));
                        etStopLoss.setSelection(etStopLoss.getText().toString().trim().length());
                    }
                }
//                if (aDouble > mStoplossMax) {
//                    String max = String.valueOf(mStoplossMax);
//                    etStopLoss.setText(String.valueOf(mStoplossMax));
//                    etStopLoss.setSelection(max.length());
//                }
            }
        });

        //查看全部交易记录
        ClickUtil.click(mTransactionRecordAll, () -> {
            if (MyAppLication.isLogin()) {
                startActivity(new Intent(mActivity, TradeActivity.class));
            } else {
                startActivity(new Intent(mActivity, LoginActivity.class));
            }
        });

        transctionDecreasePrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priceAddOrIncre = priceAddOrIncre + 0.0001;
                String formata = mFormat.format(priceAddOrIncre);
                priceAddOrIncre = Double.valueOf(formata);
                transctionPriceEditText.setText(formata);
            }
        });

        transctionIncreasePrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (priceAddOrIncre > 0.0001) {
                    priceAddOrIncre = priceAddOrIncre - 0.0001;
                    String formatb = mFormat.format(priceAddOrIncre);
                    priceAddOrIncre = Double.valueOf(formatb);
                    transctionPriceEditText.setText(formatb);
                }
            }
        });

    }

    public void upDate() {
        updateUserTitle();
        updateCoinData();
        if (mActivity.mCurrentStock != null) {
            mActivity.mTransactionFragmentUp = true;
            transctionSumEditText.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX239) + minDealNum);
            transctionPriceTextView.setVisibility(mLeftType == 1 ? View.VISIBLE : View.GONE);
            rlEditPrice.setVisibility(mLeftType == 1 ? View.GONE : View.VISIBLE);
            transctionPriceEditText.setText(String.valueOf(price));
            String type;
            if (name.contains("_")) {
                String[] split = name.split("_");
                unit = split[1];


                type = split[0];
            } else if (name.contains("/")) {
                String[] split = name.split("/");
                unit = split[1];
                type = split[0];
            } else {
                type = name;
            }
            //            mHeaderViewHolder.mSpinner.setSelection(mType == 2 ? 0 : 1);
            transactionType.setText(type);// 类型购买数量后面跟的   BTC
            mToolBar.setTitle(name.replace("_", "/"));
            transctionSumEditText.getText().clear();
            transactionCount.setText(getString(R.string.bz_count) + " " + mFormat.format(0.0) + " " + unit);

        }
    }

    private double formatDouble(Editable editable) {
        String value = editable.toString().trim();
        if (!CheckUtil.isOnlyPointNumber(value)) { //限制输入两位小数
            if (value.indexOf(".") > 0) {
                if (value.length() - value.indexOf(".") > 2) {
                    editable.delete(value.indexOf(".") + 3, value.length());
                }
            }
        }
        value = editable.toString().trim();
        return Double.valueOf(value);
    }

    /**
     * 计算总价格
     * price 单价
     * num 购买数量
     * leverage 杠杆
     * shouPer 手续费率
     * 这里的数量 已经计算了手续费（ count = （wallet * 杠杆 - wallet * 手续费） / 单价 ）
     * 计算公式 (price * num) / leverage
     */
    private double calcuAllPrice(double price, double num) {
        return (price * num) / leverage + (price * num) * shouPer; //交易额 计算公式 : 最新价*购买数量/20
    }

    private void updateCoinData() {
        if (mActivity.mCurrentStock instanceof NewStock) { //五大币
            NewStock stock = (NewStock) mActivity.mCurrentStock;
            mark = stock.getCode();
            name = stock.getCode().toUpperCase();
            //            switchPrice(stock.getBuy(), stock.getSell());
            mCurrentPriceRightD = mCurrentPriceLeftD = price = Double.valueOf(stock.getPrice());
            priceAddOrIncre = price;
            code = stock.getCode();
            mPresenter.getLeveRange(code);
            updateTopView(true);
            mPresenter.getPanKouData(code);
            if (!flag) {
                //用接口获取盘口数据
                mPresenter.initWebSocket(code);
            }
        }
        //        mPresenter.requestOrderList(code);
    }

    /**
     * 更新用户余额
     */
    private void updateUserTitle() {
        if (MyAppLication.isLogin()) { //有登陆
//            mTransactionLeftUserBalance.setText(String.format(getString(R.string.balance), wallet) + " USDT");  // 左侧可用
//            mTransactionRightUserBalance.setText(String.format(getString(R.string.balance), wallet) + " USDT");  // 右侧可用
            transactionItemBalance.setText(wallet + " USDT");  // 右侧可用
        } else { //没登录
            wallet = "0.00";
//            mTransactionLeftUserBalance.setText(String.format(getString(R.string.balance), String.valueOf("0.00")) + " USDT");
//            mTransactionRightUserBalance.setText(String.format(getString(R.string.balance), String.valueOf("0.00")) + " USDT");
            transactionItemBalance.setText("0.00 USDT");
        }
    }

    /**
     * 更新头部价格
     *
     * @param flag
     */
    public void updateTopView(boolean flag) {
        NewStock stock = (NewStock) mActivity.mCurrentStock;
        if (stock.getChange() > 0) {
            mTopStockChangeValue.setTextColor(getResources().getColor(R.color.market_up));  // 头部变化百分比
            mTopStockPrice.setTextColor(getResources().getColor(R.color.market_up));   // 当前币价钱
            transactionNowPrice.setTextColor(getResources().getColor(R.color.market_up));
            mTopStockChangeValue.setText("+" + stock.getChangeRate());
        } else {
            mTopStockChangeValue.setTextColor(getResources().getColor(R.color.market_down));
            mTopStockPrice.setTextColor(getResources().getColor(R.color.market_down));
            transactionNowPrice.setTextColor(getResources().getColor(R.color.market_up));
            mTopStockChangeValue.setText(String.valueOf(stock.getChangeRate()));
        }
        mTopStockPrice.setText(NumberUtil.keepPoint4(stock.getPrice()));  //推送价钱 --- 头部当前币价钱
        transactionNowPrice.setText(NumberUtil.keepPoint4(stock.getPrice()));
        if (flag) {
            transctionPriceTextView.setText(NumberUtil.keepPoint4(stock.getPrice()));  //  市价
        }

        mTopStockHightPrice.setText(mFormat.format(stock.getHigh()));  // 头部高
        mTopStockLowPrice.setText(mFormat.format(stock.getLow())); // 头部低
        mTransactionApproximateTop.setText(String.format(getString(R.string.approximate), NumberUtil.keep2(stock.getCnyPrice())));  // 约等于人民币
        transactionRmb.setText(String.format(getString(R.string.approximate), NumberUtil.keep2(stock.getCnyPrice())));  // 约等于人民币

    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        mSmartrefresh.finishRefresh();
        mPresenter.getLeveRange(code);
        mPresenter.getUserInfo();
        updateFragment();
    }

    /**
     * 更新当前持仓、委托 数据，
     */
    public void updateFragment() {
//        code = mActivity.mCurrentStockName;
//        if (!TextUtils.isEmpty(code)) {
//            code = code + "_usdt";
//        }
        for (Fragment fragment : mFragments) {
            ((BaseViewPagerFragment) fragment).updateData(mark);
        }
    }


    /**
     * 当用户余额获取成功
     *
     * @param wallet
     */
    public void updateWallet(String wallet) {
        this.wallet = wallet;
        upDate();
        isResume = false;
        isHideChange = false;
    }

    /**
     * 当下单成功
     *
     * @param isWeituo
     */
    public void onCreateOrderSuccess(boolean isWeituo) {
        //止盈止损初始化
        targetProfitValue.setText("");
        stopLossValue.setText("");
        etStopWin.setText("");
        etStopLoss.setText("");
        startActivity(new Intent(getActivity(), TradeActivity.class).putExtra("index", isWeituo ? 1 : 0));
    }

    /**
     * 币种杠杆信息
     *
     * @param levelBean
     */
    public void upDateLevel(LevelBean levelBean) {
        unitPrice = levelBean.getVar_price();
        multipleTabLayout.removeAllTabs();
        multipleTabLayout.clearOnTabSelectedListeners();
        //初始化杠杆选择
        if (levelBean.getLeverage() != null && !levelBean.getLeverage().isEmpty()) {
            String[] leverages = levelBean.getLeverage().split(",");
            leverage = Double.parseDouble(leverages[0]);
            for (int i = 0; i < leverages.length; i++) {
                multipleTabLayout.addTab(multipleTabLayout.newTab().setText(leverages[i]));
            }
            multipleTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    int position = tab.getPosition();
                    leverage = Double.parseDouble(leverages[position]);
                    //重新计算最大最小值
                    calcuLeftMostNum();
                    calcuRightMostNum();
                    //计算保证金
                    if (!TextUtils.isEmpty(transctionSumEditText.getText())) {
                        double valueD = formatDouble(transctionSumEditText.getText());
                        if (valueD > leftMaxNum) {
                            String maxNum = String.valueOf((int) leftMaxNum);
                            transctionSumEditText.setText(maxNum);
                            transctionSumEditText.setSelection(maxNum.length());
                        } else {
                            //交易额 计算公式 : 最新价*购买数量/20
                            mSumPrice = calcuAllPrice(mCurrentPriceLeftD, valueD);
                            transactionCount.setText(getString(R.string.bz_count) + " " + mFormat.format(mSumPrice) + " " + unit);
                            Log.i("InfoMessage", mCurrentPriceLeftD + "<<<<<<");
                        }
                    } else { //数量为空，使用最小数量
                        mSumPrice = calcuAllPrice(mCurrentPriceLeftD, minNum);
                        transactionCount.setText(getString(R.string.bz_count) + mFormat.format(mSumPrice) + unit);
                    }
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });
        }


//        multipleTabLayout.setSelectBackground(getResources().getDrawable(R.drawable.shape_border));
//        multipleTabLayout.setUnSelectBackground(getResources().getDrawable(R.drawable.shape_border));
//        multipleTabLayout.setTabData(tabs);
//        multipleTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
//            @Override
//            public void onTabSelect(int position) {
//                leverage = Double.parseDouble(leverages[position]);
//                //重新计算最大最小值
//                calcuLeftMostNum();
//                calcuRightMostNum();
//                //计算保证金
//                if (!TextUtils.isEmpty(transctionSumEditText.getText())) {
//                    double valueD = formatDouble(transctionSumEditText.getText());
//                    if (valueD > leftMaxNum) {
//                        String maxNum = String.valueOf((int) leftMaxNum);
//                        transctionSumEditText.setText(maxNum);
//                        transctionSumEditText.setSelection(maxNum.length());
//                    } else {
//                        //交易额 计算公式 : 最新价*购买数量/20
//                        mSumPrice = calcuAllPrice(mCurrentPriceLeftD, valueD);
//                        transactionCount.setText(getString(R.string.bz_count) + " " + mFormat.format(mSumPrice) + " " + unit);
//                        Log.i("InfoMessage", mCurrentPriceLeftD + "<<<<<<");
//                    }
//                } else { //数量为空，使用最小数量
//                    mSumPrice = calcuAllPrice(mCurrentPriceLeftD, minNum);
//                    transactionCount.setText(getString(R.string.bz_count) + mFormat.format(mSumPrice) + unit);
//                }
//            }
//
//            @Override
//            public void onTabReselect(int position) {
//                leverage = Double.parseDouble(leverages[position]);
//            }
//        });
        //爆仓率
        baoPer = levelBean.getTrans_ware();
        if (!levelBean.getTrans_fee().isEmpty()) {
            shouPer = Double.valueOf(levelBean.getTrans_fee().replace("%", "")) / 100;
        }
        mSpreadPrice = levelBean.getSpread() * levelBean.getVar_price();
        minNum = 0;
        minDealNum = levelBean.getNum_min();
        //        if (minDealNum == 0) {
        //            minDealNum = 1;
        //        }
        String LeftPrice = transctionPriceTextView.getText().toString().trim();
        String RightPrice = transctionPriceTextView.getText().toString().trim();
        if (!TextUtils.isEmpty(LeftPrice)) {
            mCurrentPriceLeftD = Double.valueOf(LeftPrice) + mSpreadPrice;

        }
        if (!TextUtils.isEmpty(RightPrice)) {
            mCurrentPriceRightD = Double.valueOf(RightPrice) - mSpreadPrice;
        }
        calcuLeftMostNum();
        calcuRightMostNum();

        transctionSumEditText.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX239) + minDealNum);

        mStoplossMax = (int) levelBean.getStoploss();
        mStopwinMax = (int) levelBean.getStopwin();
        targetProfitValue.setText("<=" + levelBean.getStoploss());
        stopLossValue.setText("<=" + levelBean.getStopwin());
//        etStopWin.setHint("<=" + levelBean.getStoploss());
//        etStopLoss.setHint("<=" + levelBean.getStopwin());
        etStopWin.setHint(App.INSTANCE.getString(R.string.pzy));
        etStopLoss.setHint(App.INSTANCE.getString(R.string.pzs));

    }

    private void placeOrder(int mType) {
        if (MyAppLication.isLogin()) {
            Double userBalance = Double.valueOf(wallet);
            Double sumVlaue = mSumPrice;
            if (userBalance < sumVlaue) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX276));
                return;
            }
            if (mStockBean.buynum <= 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX277));
                return;
            }
            if (mStockBean.buynum < minDealNum) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX278) + minDealNum);
                return;
            }
            //实名认证
            if (!checkIdent(getContext())) {
                return;
            }
            //设置支付密码
//            if (TextUtils.isEmpty(mActivity.mUserInfo.tpwd)) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragmentX279));
//                startActivity(new Intent(mActivity, PayPwdSettingActivity.class));
//                return;
//            }
            mStockBean.shopname = code;
            if (mActivity.mCurrency == Currency.BTC) {
                mStockBean.shopname = ((NewStock) mActivity.mCurrentStock).getCode();
            }

            int type;
            if (mStockBean.otype == 1) {//做多
                type = mType == 1 ? 0 : 1;
            } else {
                type = mType == 1 ? 2 : 3;
            }
            TipUtil.getTip(mActivity, type, mStockBean.newprice, String.valueOf(mStockBean.stopwin), String.valueOf(mStockBean.stoploss), String.valueOf(mStockBean.buynum), () -> {
                if (mActivity.mCurrency == Currency.TIME) {
                    mPresenter.createOrder(mStockBean, true, mType == 2, String.valueOf(leverage));
                } else {
                    mPresenter.createOrder(mStockBean, false, mType == 2, String.valueOf(leverage));
                }
            }).show();
            return;

        } else {
            startActivity(new Intent(mActivity, LoginActivity.class));
        }
    }

    /**
     * 计算做多可以购买的最大数 量
     * wallet 钱包总金额
     * mCurrentPriceD 当前价格
     * leverage 杠杆
     * shouPer 手续费率
     * 计算公式 (wallet * leverage - 手续费) / mCurrentPriceD
     */
    private void calcuLeftMostNum() {
        leftMaxNum = (Double.parseDouble(wallet)) / (mCurrentPriceLeftD / leverage + mCurrentPriceLeftD * shouPer);
        leftMaxNum = Math.floor(leftMaxNum);
        if (Double.isNaN(leftMaxNum) || Double.isInfinite(leftMaxNum)) {
            leftMaxNum = 0;
        }
    }

    /**
     * 计算做空可以购买的最大数量
     * wallet 钱包总金额
     * mCurrentPriceD 当前价格
     * leverage 杠杆
     * shouPer 手续费率
     * 计算公式 (wallet * leverage - 手续费) / mCurrentPriceD
     */
    private void calcuRightMostNum() {
        rightMaxNum = (Double.parseDouble(wallet)) / (mCurrentPriceRightD / leverage + mCurrentPriceRightD * shouPer);
        rightMaxNum = Math.floor(rightMaxNum);
        if (Double.isNaN(rightMaxNum) || Double.isInfinite(rightMaxNum)) {
            rightMaxNum = 0;
        }
    }

    /**
     * 获取盘口数据返回 更新盘口
     */
    public void getPanKouDataSuccess(LevelTransactionCodePk data) {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
        sellList.clear();
        buyList.clear();
        buyList.addAll(data.getAsks());
        sellList.addAll(data.getBids());

        while (sellList.size() < 5) {
            LevelTransactionCodePk.PkCode item = new LevelTransactionCodePk.PkCode();
            item.setPrice("---");
            item.setTotalSize("---");
            sellList.add(item);
        }
        while (buyList.size() < 5) {
            LevelTransactionCodePk.PkCode item = new LevelTransactionCodePk.PkCode();
            item.setPrice("---");
            item.setTotalSize("---");
            buyList.add(item);
        }

        if (sellAdapter != null) {
            sellAdapter.setNewData(sellList);
            buyAdapter.setNewData(buyList);
        } else {
            sellAdapter.notifyDataSetChanged();
            buyAdapter.notifyDataSetChanged();
        }
    }

    // 更新盘口信息
    public void update(String s) {
        Flowable.just(s)
                .compose(RxSchedulersHelper.transformer())
                .map(s1 -> GsonUtil.GsonToBean(s1, LevelTransactionCodePk.class))
                .subscribe(new NetSubScriber<LevelTransactionCodePk>() {
                    @Override
                    public void onSuccess(LevelTransactionCodePk levelTransactionCodePk) {
                        if (loadingLayout != null) {
                            loadingLayout.setVisibility(View.INVISIBLE);
                        }
                        if (sellAdapter.getData().size() > 0 && buyAdapter.getData().size() > 0) {
                            sellAdapter.notifyDataSetChanged();
                            buyAdapter.notifyDataSetChanged();
                            for (int i = 0; i < sellAdapter.getData().size(); i++) {
                                List<LevelTransactionCodePk.PkCode> list = levelTransactionCodePk.getAsks();
                                if (!list.get(i).getPrice().equals(sellAdapter.getData().get(i).getPrice()) || !list.get(i).getTotalSize().equals(sellAdapter.getData().get(i).getTotalSize())) {
                                    list.get(i).setShow(true);
                                } else {
                                    list.get(i).setShow(false);
                                }
                                sellList.set(i, list.get(i));
                            }
                            for (int i = 0; i < buyAdapter.getData().size(); i++) {
                                List<LevelTransactionCodePk.PkCode> list = levelTransactionCodePk.getBids();
                                if (!list.get(i).getPrice().equals(buyAdapter.getData().get(i).getPrice()) || !list.get(i).getTotalSize().equals(buyAdapter.getData().get(i).getTotalSize())) {
                                    list.get(i).setShow(true);
                                } else {
                                    list.get(i).setShow(false);
                                }
                                buyList.set(i, list.get(i));
                            }
                        } else {
                            sellList = levelTransactionCodePk.getBids();
                            buyList = levelTransactionCodePk.getAsks();
                            sellAdapter.setNewData(sellList);
                            buyAdapter.setNewData(buyList);
                            for (int i = 0; i < buyList.size(); i++) {
                                Log.i("info", buyList.get(i).getPrice() + "    " + buyList.get(i).getTotalSize());
                            }
                        }
                    }
                });
    }

    public void colorAnim(TextView textView, boolean update) {
        ValueAnimator animator = ValueAnimator.ofFloat(0, 3);
        animator.setDuration(300);
        animator.setRepeatCount(0);
        animator.addUpdateListener(animation -> {
            float x = (float) animation.getAnimatedValue();
            if (x == 0 && getActivity() != null) {
                textView.setBackgroundColor(getResources().getColor(R.color.red_eb_tm));
//                textView.setTextColor(getResources().getColor(R.color.white));
            } else if (x == 3 && getActivity() != null) {
//                textView.setTextColor(update ? getResources().getColor(R.color.red_eb) : getResources().getColor(R.color.gray_9e));
                textView.setBackgroundColor(getResources().getColor(R.color.background));
            }
        });
        animator.start();
    }

    public void colorAnimGreen(TextView textView, boolean update) {
        ValueAnimator animator = ValueAnimator.ofFloat(0, 3);
        animator.setDuration(300);
        animator.setRepeatCount(0);
        animator.addUpdateListener(animation -> {
            float x = (float) animation.getAnimatedValue();
            if (x == 0 && getActivity() != null) {
                textView.setBackgroundColor(getResources().getColor(R.color.app_green_tm));
//                textView.setTextColor(getResources().getColor(R.color.white));
            } else if (x == 3 && getActivity() != null) {
//                textView.setTextColor(update ? getResources().getColor(R.color.app_green) : getResources().getColor(R.color.gray_9e));
                textView.setBackgroundColor(getResources().getColor(R.color.background));
            }
        });
        animator.start();
    }


}
